package com.example.newspublish.service.impl;

import com.example.newspublish.exception.NewsServiceException;
import com.example.newspublish.mapper.CategoryMapper;
import com.example.newspublish.pojo.entity.Category;
import com.example.newspublish.pojo.form.CategoryForm;
import com.example.newspublish.pojo.result.ResultCodeEnum;
import com.example.newspublish.service.CategoryService;
import com.example.newspublish.util.result.Result;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public Result addCategory(CategoryForm categoryForm) {
        int row = categoryMapper.addCategory(categoryForm);
        if (row == 1) {
            System.out.println("添加分类成功~");
            return Result.success("添加分类成功~",null);
        }
        else {
            System.out.println("添加失败！该名称已存在~");
            return Result.failed(20001,"添加失败！该名称已存在~");
        }
    }

    @Override
    public Result getCategoryList() {
        List<Category> categoryList = categoryMapper.getCategoryList();
        return Result.success("",categoryList);
    }

    @Override
    public Result deleteCategoryById(Long id) {

        Category category = categoryMapper.selectById(id);
        if(!ObjectUtils.isNotEmpty(category)) {
            throw new NewsServiceException(ResultCodeEnum.FAIL, "新闻分类id不存在");
        }
        int row = categoryMapper.deleteCategoryById(id);
        if (row == 1) {
            System.out.println("删除分类成功~");
            return Result.success("删除分类成功~",null);
        }
        else {
            System.out.println("删除失败~");
            return Result.failed(20001,"删除失败~");
        }
    }

    @Override
    public Result updateCategoryById(Long id, String categoryName) {

        int row = categoryMapper.isExistCategoryByName(categoryName);

        if (row != 0) {
            return Result.failed(20001,"修改失败");
        }
        else {
            categoryMapper.updateCategoryById(id,categoryName);
            System.out.println("修改分类成功~ row: "+row);
            return Result.success("修改分类成功~",null);
        }
    }
}
